<template>
  <div class="report-share-page">
    <div v-if="loading" class="page-container">
      <div class="loading-wrapper">
        <div class="loading-spinner"></div>
        <p>加载中...</p>
      </div>
    </div>
    
    <div v-else-if="error" class="page-container">
      <div class="error-wrapper">
        <h1>报表不存在</h1>
        <p>{{ error }}</p>
      </div>
    </div>
    
    <div v-else class="page-container">
      <div class="share-content">
        <!-- 页面头部 -->
        <div class="share-header">
          <h1>{{ reportData.title || reportData.template_name || '报表详情' }}</h1>
          <div class="subtitle">报表详情页面</div>
        </div>
        
        <!-- 基本信息 -->
        <div class="info-section">
          <h2>基本信息</h2>
          <div class="info-grid">
            <div class="info-item">
              <div class="info-label">模板名称</div>
              <div class="info-value">{{ getTemplateName(reportData.template_code) }}</div>
            </div>
            <div class="info-item">
              <div class="info-label">运行状态</div>
              <div class="info-value">
                <span :class="['status-badge', `status-${reportData.status}`]">
                  {{ getStatusText(reportData.status) }}
                </span>
              </div>
            </div>
            <div class="info-item">
              <div class="info-label">统计时间</div>
              <div class="info-value">
                <span v-if="reportData.time_start && reportData.time_end &&
                            reportData.time_start !== 'None' && reportData.time_end !== 'None' &&
                            reportData.time_start !== 'null' && reportData.time_end !== 'null'">
                  {{ formatDateTime(reportData.time_start) }} ~ {{ formatDateTime(reportData.time_end) }}
                </span>
                <span v-else style="color: #409eff; font-weight: 500;">全部数据</span>
              </div>
            </div>
            <div class="info-item">
              <div class="info-label">创建时间</div>
              <div class="info-value">{{ formatDateTime(reportData.created_at) }}</div>
            </div>
            <div class="info-item">
              <div class="info-label">完成时间</div>
              <div class="info-value">{{ reportData.finished_at ? formatDateTime(reportData.finished_at) : '-' }}</div>
            </div>
            <div class="info-item">
              <div class="info-label">执行耗时</div>
              <div class="info-value duration-value">{{ calculateDuration(reportData.created_at, reportData.finished_at) }}</div>
            </div>
          </div>
        </div>
        
        <!-- 错误信息 -->
        <div v-if="reportData.error_message" class="error-alert">
          <strong>错误信息：</strong>{{ reportData.error_message }}
        </div>
        
        <!-- 文件列表 -->
        <div class="files-section">
          <h2>生成的文件</h2>
          <table v-if="reportData.files && reportData.files.length > 0" class="files-table">
            <thead>
              <tr>
                <th>文件类型</th>
                <th>文件大小</th>
                <th>创建时间</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="file in reportData.files" :key="file.id">
                <td>
                  <span :class="['file-type-badge', `file-type-${file.file_type}`]">
                    {{ file.file_type.toUpperCase() }}
                  </span>
                </td>
                <td>{{ formatFileSize(file.file_size) }}</td>
                <td>{{ formatDateTime(file.created_at) }}</td>
                <td>
                  <a
                    v-if="file.previewable"
                    :href="getPreviewUrl(reportData.id, file.id)"
                    target="_blank"
                    class="btn btn-primary"
                  >
                    预览
                  </a>
                  <a
                    :href="getDownloadUrl(reportData.id, file.id)"
                    class="btn btn-secondary"
                  >
                    下载
                  </a>
                </td>
              </tr>
            </tbody>
          </table>
          <div v-else class="empty-state">
            <div class="empty-state-icon">📄</div>
            <div>暂无文件</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
// @ts-ignore
import api from '@/utils/api.js'
// @ts-ignore
import { createLogger } from '@/utils/logger.js'

const componentLogger = createLogger('ReportShare')
const route = useRoute()

const runId = ref(null)
const loading = ref(true)
const error = ref(null)
const reportData = ref({})
const templates = ref([])

// 获取模板列表
const fetchTemplates = async () => {
  try {
    const response = await api.get('/reports/templates')
    if (response.data.success) {
      // 处理不同的数据结构（可能返回 data.rows 或直接返回 data）
      const data = response.data.data || {}
      templates.value = data.rows || data || []
    }
  } catch (err) {
    componentLogger.warn('获取模板列表失败', err)
  }
}

// 获取模板名称
const getTemplateName = (code) => {
  if (!code) return '未知模板'
  const template = templates.value.find(t => t.template_code === code)
  return template ? template.template_name : code
}

// 获取报表数据
const fetchReportData = async () => {
  try {
    loading.value = true
    error.value = null
    
    // 同时获取模板列表和报表数据
    await Promise.all([
      fetchTemplates(),
      (async () => {
        const response = await api.get(`/reports/runs/${runId.value}`)
        if (response.data.success) {
          reportData.value = response.data.data
          // 后端API已经返回了files字段，如果没有则初始化为空数组
          if (!reportData.value.files) {
            reportData.value.files = []
          }
          componentLogger.info('报表数据加载成功', reportData.value)
        } else {
          error.value = response.data.message || '加载失败'
        }
      })()
    ])
  } catch (err) {
    componentLogger.error('加载报表数据失败', err)
    error.value = err.response?.data?.message || err.message || '加载失败'
  } finally {
    loading.value = false
  }
}

// 格式化日期时间（支持多种格式）
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  
  try {
    let date
    if (typeof dateTime === 'string') {
      // 处理GMT格式的日期字符串（如 "Mon, 10 Nov 2025 16:43:22 GMT"）
      if (dateTime.includes('GMT') || dateTime.includes('UTC')) {
        date = new Date(dateTime)
      } else if (dateTime.match(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/)) {
        // 已经是格式化好的字符串，直接返回
        return dateTime
      } else {
        // 尝试解析其他格式
        date = new Date(dateTime)
      }
    } else if (dateTime instanceof Date) {
      date = dateTime
    } else {
      return String(dateTime)
    }
    
    // 检查日期是否有效
    if (isNaN(date.getTime())) {
      return String(dateTime)
    }
    
    // 格式化为中文格式
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')
    
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  } catch (err) {
    componentLogger.warn('日期格式化失败', { dateTime, error: err })
    return String(dateTime)
  }
}

// 格式化文件大小
const formatFileSize = (size) => {
  if (!size) return '0 B'
  const units = ['B', 'KB', 'MB', 'GB']
  let index = 0
  let fileSize = Number(size)
  while (fileSize >= 1024 && index < units.length - 1) {
    fileSize /= 1024
    index++
  }
  return `${fileSize.toFixed(2)} ${units[index]}`
}

// 计算执行耗时
const calculateDuration = (startTime, endTime) => {
  if (!startTime || !endTime) return '-'
  try {
    const start = new Date(startTime)
    const end = new Date(endTime)
    const duration = end - start
    const seconds = Math.floor(duration / 1000)
    const minutes = Math.floor(seconds / 60)
    const hours = Math.floor(minutes / 60)
    const days = Math.floor(hours / 24)
    
    if (days > 0) {
      return `${days}天${hours % 24}时`
    } else if (hours > 0) {
      return `${hours}时${minutes % 60}分`
    } else if (minutes > 0) {
      return `${minutes}分${seconds % 60}秒`
    } else {
      return `${seconds}秒`
    }
  } catch {
    return '-'
  }
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    success: '成功',
    running: '运行中',
    failed: '失败',
    queued: '排队中'
  }
  return statusMap[status] || status || '未知'
}

// 获取预览URL（使用前端路由）
const getPreviewUrl = (runId, fileId) => {
  return `/#/reports/preview/${runId}/${fileId}`
}

// 获取下载URL
const getDownloadUrl = (runId, fileId) => {
  return `/api/reports/runs/${runId}/files/${fileId}/download`
}

onMounted(() => {
  runId.value = route.params.runId
  if (runId.value) {
    fetchReportData()
  } else {
    error.value = '缺少报表ID'
    loading.value = false
  }
})
</script>

<style>
/* 全局样式 - 确保分享页面全屏独立显示 */
.report-share-page {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100vw;
  height: 100vh;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  overflow-y: auto;
  z-index: 9999;
  margin: 0;
  box-sizing: border-box;
}

/* 隐藏body滚动条（仅在分享页面） */
body:has(.report-share-page) {
  overflow: hidden;
}

.page-container {
  max-width: 1200px;
  margin: 0 auto;
  height: 100%;
}

.loading-wrapper,
.error-wrapper {
  background: white;
  border-radius: 12px;
  padding: 60px;
  box-shadow: 0 10px 40px rgba(0,0,0,0.2);
  text-align: center;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #667eea;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 20px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error-wrapper h1 {
  color: #dc3545;
  margin-bottom: 10px;
  font-size: 24px;
}

.error-wrapper p {
  color: #666;
  margin-bottom: 20px;
}

.share-content {
  background: white;
  border-radius: 12px;
  box-shadow: 0 10px 40px rgba(0,0,0,0.2);
  overflow: hidden;
}

.share-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 30px;
  text-align: center;
}

.share-header h1 {
  font-size: 28px;
  margin-bottom: 10px;
  font-weight: 600;
}

.share-header .subtitle {
  font-size: 14px;
  opacity: 0.9;
}

.info-section {
  background: #f8f9fa;
  padding: 30px;
  margin: 0;
}

.info-section h2 {
  font-size: 20px;
  color: #333;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid #667eea;
}

.info-grid {
  display: flex;
  flex-direction: column;
}

.info-item {
  display: flex;
  flex-direction: row;
  align-items: center;
  padding: 14px 0;
  border-bottom: 1px solid #e9ecef;
}

.info-item:last-child {
  border-bottom: none;
}

.info-label {
  font-size: 13px;
  color: #666;
  text-transform: uppercase;
  letter-spacing: 0.5px;
  font-weight: 600;
  min-width: 100px;
  width: 100px;
  flex-shrink: 0;
  padding-right: 12px;
  line-height: 20px; /* 与状态徽标高度保持一致，保证各行垂直对齐 */
}

.info-value {
  font-size: 15px;
  color: #333;
  font-weight: 500;
  flex: 0 0 auto;
  display: flex;
  align-items: center;
  line-height: 20px; /* 统一行高，避免"运行状态"行与其他行不对齐 */
}

.duration-value {
  color: #667eea;
  font-weight: 600;
}

.status-badge {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 2px 10px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
  line-height: 20px;
  height: 20px;
  box-sizing: border-box;
}

.info-section .status-badge {
  position: static;      /* 覆盖全局绝对定位，保持在当前行内 */
  top: auto;
  right: auto;
  white-space: nowrap;   /* 防止中文在窄宽度时换行 */
}

.status-success {
  background: #d4edda;
  color: #155724;
}

.status-running {
  background: #fff3cd;
  color: #856404;
}

.status-failed {
  background: #f8d7da;
  color: #721c24;
}

.files-section {
  padding: 30px;
  margin: 0;
}

.files-section h2 {
  font-size: 20px;
  color: #333;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid #667eea;
}

.files-table {
  width: 100%;
  border-collapse: collapse;
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.files-table thead {
  background: #667eea;
  color: white;
}

.files-table th {
  padding: 15px;
  text-align: left;
  font-weight: 500;
  font-size: 14px;
}

.files-table td {
  padding: 15px;
  border-bottom: 1px solid #e9ecef;
}

.files-table tbody tr:hover {
  background: #f8f9fa;
}

.file-type-badge {
  display: inline-block;
  padding: 4px 10px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
  text-transform: uppercase;
}

.file-type-html {
  background: #e3f2fd;
  color: #1976d2;
}

.file-type-excel {
  background: #e8f5e9;
  color: #388e3c;
}

.btn {
  display: inline-block;
  padding: 8px 16px;
  border-radius: 4px;
  text-decoration: none;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  border: none;
  transition: all 0.3s;
  margin-right: 8px;
}

.btn-primary {
  background: #667eea;
  color: white;
}

.btn-primary:hover {
  background: #5568d3;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(102, 126, 234, 0.3);
}

.btn-secondary {
  background: #6c757d;
  color: white;
}

.btn-secondary:hover {
  background: #5a6268;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(108, 117, 125, 0.3);
}

.error-alert {
  background: #f8d7da;
  color: #721c24;
  padding: 15px;
  border-radius: 8px;
  margin: 20px 30px;
  border-left: 4px solid #dc3545;
}

.empty-state {
  text-align: center;
  padding: 40px;
  color: #999;
}

.empty-state-icon {
  font-size: 48px;
  margin-bottom: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .report-share-page {
    padding: 10px;
  }
  
  .share-header h1 {
    font-size: 24px;
  }
  
  .info-grid {
    grid-template-columns: 1fr;
  }
  
  .files-table {
    font-size: 14px;
  }
  
  .files-table th,
  .files-table td {
    padding: 10px;
  }
}
</style>

